<script setup>
    import { ref, reactive, computed, toRaw } from 'vue'
    import { getCode, register, login, menuPermissions } from '../../api';
    import { useRouter } from 'vue-router'
    import { useStore } from 'vuex';
    import { el } from 'element-plus/es/locale/index.mjs';

    const imgUrl = new URL('../../../public/login.jpg', import.meta.url).href
    const router = useRouter()
    const store = useStore()

    const routerList = computed(() => store.state.menu.routerList)
    //表单数据
    const loginForm = reactive({
        userName: '',
        passWord: '',
        validCode: ''
    })

    //切换表单(0登录 1注册)
    const formType = ref(0)
    //切换登录和注册
    const handleChange = () => {
        formType.value = formType.value ? 0 : 1
    }

    //账号校验规则
    const validatorUser = (rule, value, callback) => {
        if (!value) {
            callback(new Error('请输入账号'))
        } else {
            const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
            phoneReg.test(loginForm.userName) ? callback() : callback(new Error('请输入正确的手机号'))
        }
    }

    //密码校验规则
    const validatorPwd = (rule, value, callback) => {
        if (!value) {
            callback(new Error('请输入密码'))
        } else {
            const pwdReg = /^[a-zA-Z0-9_-]{4,16}$/
            pwdReg.test(loginForm.passWord) ? callback() : callback(new Error('密码格式错误！请输入4-16位字母、数字、下划线或减号'))
        }
    }
    //表单校验
    const rules = reactive({
        //失去焦点后出发校验
        userName: [{ validator: validatorUser, trigger: 'blur' }],
        passWord: [{ validator: validatorPwd, trigger: 'blur' }],
    })

    //发送短信
    const countdown = reactive({
        validText: '获取验证码',
        time: 60
    })

    let flag = false
    const countdownChange = () => {
        //如果已发送则不处理
        if (flag) return
        //判断手机号是否合法
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
            return ElMessage({
                message: '请检查手机号是否正确',
                type: 'warning',
            })
        }
        //倒计时
        const timer = setInterval(() => {
            if (countdown.time <= 0) {
                countdown.validText = '获取验证码'
                countdown.time = 60
                flag = false
                //停止计时器
                clearInterval(timer)
            } else {
                countdown.time--
                countdown.validText = `剩余${countdown.time}s`
            }
        }, 1000)
        flag = true
        getCode({ tel: loginForm.userName }).then(({ data }) => {
            if (data.code === 10000) {
                ElMessage.success("验证码发送成功")
            }
        })
    }

    const loginFormRef = ref()

    //表单提交
    const subimtForm = async (formEl) => {
        if (!formEl) return
        //手动触发校验
        await formEl.validate((valid, fields) => {
            if (valid) {
                console.log(loginForm, 'submit!')
                //注册页面
                if (formType.value) {
                    register(loginForm).then(({ data }) => {
                        if (data.code === 10000) {
                            ElMessage.success("注册成功")
                            formType.value = 0
                        }
                    })
                } else {
                    //登录页面
                    login(loginForm).then(({ data }) => {
                        if (data.code === 10000) {
                            ElMessage.success("登录成功")
                            console.log(data);
                            //将token和用户信息缓存到浏览器
                            localStorage.setItem('pz_token', data.data.token)
                            localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
                            //获取用户菜单权限
                            menuPermissions().then(({ data }) => {
                                store.commit('dynamicMenu', data.data)
                                console.log('routerList', routerList);
                                //动态添加路由
                                toRaw(routerList.value).forEach(item => {
                                    router.addRoute('main', item)
                                })
                                router.push('/')
                            })

                        }
                    })
                }
            } else {
                console.log('error submit!', fields)
            }
        })
    }
</script>

<template>
    <el-row class="login-container">
        <el-card class="login-card">
            <template #header>
                <div class="card-header">
                    <img :src="imgUrl" alt="">
                </div>
            </template>
            <div class="jump-link">
                <el-link type="primary" @click="handleChange">{{ formType ? '返回登录' : '注册账号' }}</el-link>
            </div>
            <el-form ref="loginFormRef" :model="loginForm" style="max-width: 600px" :rules="rules">

                <el-form-item prop="userName">
                    <el-input v-model="loginForm.userName" prefix-icon="UserFilled" placeholder="手机号"></el-input>
                </el-form-item>

                <el-form-item prop="passWord">
                    <el-input v-model="loginForm.passWord" type="password" prefix-icon="Lock"
                        placeholder="密码"></el-input>
                </el-form-item>

                <el-form-item v-if="formType" prop="validCode">
                    <el-input v-model="loginForm.validCode" prefix-icon="Lock" placeholder="验证码">
                        <template #append>
                            <span style="cursor: pointer" @click="countdownChange">{{ countdown.validText }}</span>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" :style="{ width: '100%' }" @click="subimtForm(loginFormRef)">
                        {{ formType ? '注册' : '登录' }}
                    </el-button>
                </el-form-item>

            </el-form>
        </el-card>
    </el-row>

</template>

<style lang="less" scoped>
    :deep(.el-card__header) {
        padding: 0;
    }

    .login-container {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        .login-card {
            width: 480px;
        }

        .card-header {
            height: 150px;

            img {
                height: 100%;
                width: 100%;
            }
        }

        .jump-link {
            text-align: right;
            margin-bottom: 10px;
        }
    }


</style>